#include "widget_script_tree.h"
#include "ui_widget_script_tree.h"
#include "../Program.h"
#include <QDragEnterEvent>
#include <QMimeData>
#include <QFileInfo>
#include <QMenu>

WidgetScriptTree::WidgetScriptTree(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::WidgetScriptTree)
{
    ui->setupUi(this);
    connect(ui->listWidget, &QListWidget::currentRowChanged, this, &WidgetScriptTree::listWidget_currentRowChanged);
    connect(ui->listWidget, &QListWidget::itemChanged, this, &WidgetScriptTree::listWidget_itemChanged);

    _contextMenu = new QMenu(this);
    _actionNew = new QAction(tr("新建"), this);
    _actionDelete = new QAction(tr("删除"), this);
    _actionRename = new QAction(tr("重命名"), this);
    _actionMoveUp = new QAction(tr("上移"), this);
    _actionMoveDown = new QAction(tr("下移"), this);
    connect(_actionNew, &QAction::triggered, this, &WidgetScriptTree::actionNew_triggered);
    connect(_actionDelete, &QAction::triggered, this, &WidgetScriptTree::actionDelete_triggered);
    connect(_actionRename, &QAction::triggered, this, &WidgetScriptTree::actionRename_triggered);
    connect(_actionMoveUp, &QAction::triggered, this, &WidgetScriptTree::actionMoveUp_triggered);
    connect(_actionMoveDown, &QAction::triggered, this, &WidgetScriptTree::actionMoveDown_triggered);
}

WidgetScriptTree::~WidgetScriptTree()
{
    delete ui;
}

/**
 * @brief 加载脚本列表
 */
void WidgetScriptTree::LoadScript()
{
    ui->listWidget->clear();
    for (qsizetype i = 0; i < Program::UserScript.size(); i++) addItem(i);
    emit sig_scriptSelected(Program::UserScript.isEmpty() ? -1 : 0);
}

/**
 * @brief 文件拖入
 * @param event
 */
void WidgetScriptTree::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasUrls()) event->acceptProposedAction();
    else event->ignore();
}

/**
 * @brief 文件拖入释放
 * @param event
 */
void WidgetScriptTree::dropEvent(QDropEvent *event)
{
    QList<QUrl> files = event->mimeData()->urls();
    for (qsizetype i = 0; i < files.count(); i++)
    {
        QString path = files[i].toLocalFile();
        QFileInfo fileInfo(path);
        if (fileInfo.suffix().toUpper() == "LUA")
        {
            QFile file(path);
            if (file.open(QIODevice::ReadOnly | QIODevice::Text))
            {
                QTextStream in(&file);
                QString content = in.readAll();
                file.close();
                QString name = fileInfo.completeBaseName();
                Program::UserScript.append(QPair<QString, QString>(name, content));
                addItem(Program::UserScript.size() - 1);
            }
        }
    }
}

/**
 * @brief 右键菜单
 * @param event
 */
void WidgetScriptTree::on_listWidget_customContextMenuRequested(const QPoint &pos)
{
    _contextMenu->clear();
    _contextMenu->addAction(_actionNew);
    if (ui->listWidget->itemAt(pos) != nullptr)
    {
        _contextMenu->addAction(_actionDelete);
        _contextMenu->addAction(_actionRename);
        _contextMenu->addAction(_actionMoveUp);
        _contextMenu->addAction(_actionMoveDown);
    }
    _contextMenu->exec(QCursor::pos());
}

/**
 * @brief 列表选择改变
 * @param currentRow
 */
void WidgetScriptTree::listWidget_currentRowChanged(int currentRow)
{
    if (currentRow >= 0)
    {
        emit sig_scriptSelected(currentRow);
    }
}

/**
 * @brief 修改了脚本名称
 * @param item
 */
void WidgetScriptTree::listWidget_itemChanged(QListWidgetItem *item)
{
    int index = ui->listWidget->row(item);
    Program::UserScript[index].first.assign(item->text());
}

/**
 * @brief 新建脚本
 */
void WidgetScriptTree::actionNew_triggered()
{
    int index = Program::UserScript.size();
    Program::UserScript.append(QPair<QString, QString>("用户脚本", ""));
    QListWidgetItem* item = addItem(index);
    ui->listWidget->editItem(item);
    ui->listWidget->setCurrentItem(item);
}

/**
 * @brief 删除脚本
 */
void WidgetScriptTree::actionDelete_triggered()
{
    QListWidgetItem* item = ui->listWidget->currentItem();
    if (item)
    {
        int index = ui->listWidget->row(item);
        Program::UserScript.removeAt(index);
        ui->listWidget->removeItemWidget(item);
        delete item;
    }
}

/**
 * @brief 重命名脚本
 */
void WidgetScriptTree::actionRename_triggered()
{
    QListWidgetItem* item = ui->listWidget->currentItem();
    if (item)
    {
        ui->listWidget->editItem(item);
    }
}

/**
 * @brief 向上移动脚本排序
 */
void WidgetScriptTree::actionMoveUp_triggered()
{
    QListWidgetItem* item = ui->listWidget->currentItem();
    if (item)
    {
        int index = ui->listWidget->row(item);
        if (index > 0)
        {
            Program::UserScript.swapItemsAt(index, index - 1);
            ui->listWidget->insertItem(index - 1, ui->listWidget->takeItem(index));
            ui->listWidget->setCurrentRow(index - 1);
        }
    }
}

/**
 * @brief 向下移动脚本排序
 */
void WidgetScriptTree::actionMoveDown_triggered()
{
    QListWidgetItem* item = ui->listWidget->currentItem();
    if (item)
    {
        int index = ui->listWidget->row(item);
        if (index < ui->listWidget->count() - 1)
        {
            Program::UserScript.swapItemsAt(index, index + 1);
            ui->listWidget->insertItem(index + 1, ui->listWidget->takeItem(index));
            ui->listWidget->setCurrentRow(index + 1);
        }
    }
}

/**
 * @brief 添加列表项
 * @param index
 */
QListWidgetItem* WidgetScriptTree::addItem(int index)
{
    QListWidgetItem* item = new QListWidgetItem();
    item->setText(Program::UserScript[index].first);
    item->setIcon(QIcon(":/resource/icon/common/lua.png"));
    item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
    ui->listWidget->addItem(item);
    return item;
}
